package com.cy.api;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

public class ThreadPoolExecutorTests {
    //创建任务队列，存储待执行的任务
    static BlockingQueue<Runnable> workQueue=
            new ArrayBlockingQueue<>(3);
    //构建线程工厂
    static ThreadFactory threadFactory=new ThreadFactory() {
        //线程名前缀
        private String prefix="pool-thread-task-";
        //定义一个提供了自增自减机制的对象
        private AtomicLong atomicLong=new AtomicLong(1);

        /**
         * atomicLong.getAndIncrement() 从1开始，每次+1（线程安全）
         */
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r,prefix+atomicLong.getAndIncrement());
        }
    };
    public static void main(String[] args) {
        ThreadPoolExecutor tpool=new ThreadPoolExecutor(2,
                3,//最大线程数
                3,//执行时间
                TimeUnit.SECONDS,          workQueue,//任务队列
                threadFactory,
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        tpool.execute(new Runnable() {
            @Override
            public void run() {
                String task=Thread.currentThread().getName()+"->task01";
                System.out.println(task);
                    try {
                        Thread.sleep(3);
                       // return new Thread();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
            }
        });
    }
}
